<?php
namespace app\home\controller;
use \app\common\controller\Homebase;
use \think\Loader;

class Pages extends Basic{
	public function _initialize()
    {
        $this->pages  = Loader::model('Pages');
        $arr[0]['text']='页面列表';
        $arr[0]['url']='index';
        $this->assign('third_menu', $arr);
    }
	public function index(){
		
		$list = $this->pages->paginate(10);
		$this->assign('list', $list);
        return $this->fetch();
	}
	public function add(){
		if(IS_POST){
			$post = input('');
			$type = $post['type'];
			switch($type){
				case 0:
					$post['content_cn'] = $post["uEditor"];
					$post['attach_cn'] = "";
				break;
				case 1:
					$post['content_cn'] = $this->makeControllerTemplate($post["attach_cn"]);
				break;
				default:
				break;
			}
			$res = $this->pages->savePages($post);
			if($res['code']){
				return $this->ret->setCode(0)->setMsg("保存成功")->setAsk("保存成功，是否继续？")->toJson();				
			}else{
				return $this->ret->setCode(1)->setMsg($res['msg'])->toJson();
			}
		}else{
			return $this->fetch('add');
		}
	}
	public function edit($id = 0){
	    $page = $this->pages->find($id);
        if (IS_POST) {
            $post = input('');
            $type = $post['type'];
            switch ($type) {
                case 0:
                    $post['content_cn'] = $post["uEditor"];
                    $post['attach_cn'] = "";
                    break;
                case 1:
                    $post['content_cn'] = $this->makeControllerTemplate($post["attach_cn"]);
                    break;
                default:
                    break;
            }
            $res = $this->pages->savePages($post, $id);
            if ($res['code']) {
                return $this->ret->setCode(0)->setMsg("保存成功")->setAsk("保存成功，是否继续？")->toJson();
            } else {
                return $this->ret->setCode(1)->setMsg($res['msg'])->toJson();
            }
        } else {
            $this->assign("page", $page);
            return $this->fetch('edit');
        }

    }

    public function del($id){
        $res = $this->pages->where("id",'=',$id)->delete();
        if ($res) {
            return $this->ret->setCode(0)->setMsg('删除成功')->setReload()->toJson();
        } else {
            return $this->ret->setCode(1)->setMsg('删除失败')->toJson();
        }

    }
	//解析后台Controller模板
	private function makeControllerTemplate($templateFilePath){
		$fileContent = $this->fetch($templateFilePath);
		return $fileContent;
	}
}